//
//  WBMainViewController.swift
//  MyWeibo
//
//  Created by timw on 2017/3/16.
//  Copyright © 2017年 wuqc. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    // 定时器
    fileprivate var timer: Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        // 设置代理
        delegate = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)

    }
    
    deinit {
        // 销毁时钟
        timer?.invalidate()
        
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /**
     portrait: 竖屏，肖像
     landscape: 横屏，风景画
     - 使用代码控制设备的方向，好处，可以在需要横屏的时候单独处理！
     - 设置支持的方向后，当前的控制器及子控制器都会遵守这个方向！
     - 如果播放视频，通常是通过modal展现的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: - 登录通知监听
    @objc fileprivate func userLogin() {
        print("登录通知")
        
        // 展现控制器 -  通常会和 UINavigationController一起用，方便返回
        let nav = UINavigationController(rootViewController: WBOAuthViewController())
        
        present(nav, animated: true, completion: nil)
        
    }
    
    @objc fileprivate func composeStatus() {
        print("发布")
        // FIXME:等待实现
        
        // 测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.red
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
        
    }
    
    // MARK: - 私有控件
    // 发布按钮
    fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}


// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate {
    /// 将要选择TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        
        // 1> 获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        // 2> 判断当前索引是首页，同时idx也是首页，重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            // 3>让表格滚动到顶部
            // a) 获取控制器
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController

            // b） 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            // 4. 刷新数据,增加延迟，保证比哦啊哥先滚动到顶部再刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            

        }
        return !viewController.isMember(of: UIViewController.self)
    }
}


extension WBMainViewController {

    /// 定义时钟
    fileprivate func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟触发方法
    @objc private func updateTimer() {
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            print("有\(count)条微博")
            /// 设置首页 tabBarItem的badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            // 设置app的badgeNumber
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }

}

// extension 类似于 OC 中的分类，在Swift中还可以用来切分代码块
// 可以把相近功能的函数，放在一个 extension 中
// 便于代码维护
// 注意: 和 OC的分类一样，extension 中不能定义属性
// MARK -  设置界面

extension WBMainViewController {
    /// 设置发布按钮
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        
        // 将向内缩进的宽度减少，能够让按钮的宽度变大，盖住容错点，防止穿帮,通过代理判断是否时viewController，如果是就不做动作
        let w = tabBar.bounds.width / count
        
        // CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        // 按键监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    //设置所有子控制器
    fileprivate func setupChildControllers() {
//        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
//        let data = NSData(contentsOfFile: path),
//        let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: AnyObject]]
//            else {
//            return
//        }
        
        // 在现在很多网络引用程序中，界面的的创建都依赖网络的json
//        let array: [[String: Any]] = [
//            ["clsName": "WBHomeViewController","title": "首页","imageName": "home","visitorInfo": ["imageName": "", "message": "关注一些人，回这里看看有什么惊喜"]],
//            ["clsName": "WBMessageViewController","title": "消息","imageName": "message_center","visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登陆后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            ["clsName": "UIViewController"],
//            ["clsName": "WBDiscoverViewController","title": "发现","imageName": "discover","visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后最新最热微博尽在掌握，不会再与实事潮流擦肩而过"]],
//            ["clsName": "WBHomeViewController","title": "我","imageName": "profile","visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]],
//        ]
        
        //测试数据格式是否正确
//        (array as NSArray).write(toFile: "/Users/timw/Desktop/demo.plist", atomically: true)
        // 数组 -> json 序列化
       //let data = try! JSONSerialization.data(withJSONObject: array, options: [])
        //(data as NSData).write(toFile: "/Users/timw/Desktop/demo.json", atomically: true)
        
        // 0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断data是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // data 一定会有一个内容，反序列化,转成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else{
                return
        }
        // 遍历数组,循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - parameter dict: 信息字典:[clsName,title,imageName,visitorInfo]
    ///
    /// - returns: 子控制器
   fileprivate func controller(dict:[String: Any]) ->  UIViewController {
    
    // 1. 取得字典内容
    guard let clsName = dict["clsName"] as? String,
        let title = dict["title"]as? String,
        let imageName = dict["imageName"]as? String,
        let cls =  NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String: String]
         else {
            return UIViewController()
    }
        
    // 2. 创建视图控制器
    let vc = cls.init()
    vc.title = title
    
    // 设置控制器的访客信息字典
    vc.visitorInfoDictionary = visitorDict
    
    // 3.设置图像
    vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
    vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
    
    // 4.设置字体颜色和大小
    vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
    // 系统默认的是12号字 ，修改字体大小，要设置 Normal 的字体大小
    vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: .normal)
   
    let nav = WBNavigationController(rootViewController: vc)
    return nav
    }
    
}
